const Controllers = require('../../controllers/Controller.js').controller;
const dateTimePicker = require('../../../utils/dateTimePicker.js');
const util = require('../../../utils/util.js');
Page({
  data: {
    name:'',
    startTime:'请选择时间',
    endTime:'请选择时间',
    dateTimeArray1: '',
    dateTime1: '',
    dateTimeArray2: '',
    dateTime2: '',
    typeattr:['套餐卡','充值活动卡'],
    type:0,
    typeval:'套餐卡',
    price:'',
    cost:'',
    timeState:0,
    effectiveTime:'',
    joinProduct:[],
    haveGivePrice:0,
    haveGiveIntegral:0,
    desc:'',
    currentDate:util.formatTime_1(new Date()),
    isloading:false,
    isShow:false,
    couponList:[],
    vipTypeList:[
      {
        name:"普通会员",
        id:1
      },
      {
        name:"VIP会员",
        id:0
      }
    ],
    vipIndex:0,
    totalNum:"",
    goodsNum:0,
    goodsTotalPrice:0,
    addCouponList:[],
    payLimit:0,
    explain:"",
    rewardState:0,
    rewardPrice:'',
    rewardProportion:'',
  },

  // 获取协议说明
  getListByTypes(){
    let value={}
    if(this.data.type==5){
      value.types=27
    }else{
      value.types=26
    }
    Controllers.getListByTypes(value).then(res=>{
      this.setData({
        explain:res.data[0].content
      })
    })
  },


  //增加优惠券
  addCouponNum(e){
    let index=e.currentTarget.dataset.index
    let list=this.data.addCouponList
    list[index].selectNum=list[index].selectNum+1
    this.setData({
      addCouponList:list
    })
    this.computedCost()
  },

  //减少优惠券
  reduceNum(e){
    let index=e.currentTarget.dataset.index
    let list=this.data.addCouponList
    if(list[index].selectNum>1){
      list[index].selectNum=list[index].selectNum-1
    }
    this.setData({
      addCouponList:list
    })
    this.computedCost()
  },

  computedCost(){
    let totalNum=0
    let goodsNum=0
    let goodsTotalPrice=0
    let cost=0
    let goodsList=this.data.joinProduct
    let addCouponList=this.data.addCouponList
    goodsList.forEach(item=>{
      goodsNum=goodsNum+item.num
      totalNum=totalNum+item.num
      goodsTotalPrice=goodsTotalPrice+item.price*item.num
      cost=cost+item.price*item.num
    })
    addCouponList.forEach(item=>{
      totalNum=totalNum+item.selectNum
      cost=cost+item.price*item.selectNum
    })
    this.setData({
      goodsNum:goodsNum,
      goodsTotalPrice:goodsTotalPrice,
      totalNum:totalNum,
      cost:cost
    })
  },

  //删除
  delect(e){
    let index = e.currentTarget.dataset['index'];
    let addCouponList = this.data.addCouponList
    addCouponList.splice(index,1)
    this.setData({
      addCouponList
    })
    if(this.data.addCouponList.length>0){
      this.setData({
        isGiveCoupon:true
      })
    }else{
      this.setData({
        isGiveCoupon:false
      })
    }

    this.computedCost()
  },

  //选择优惠券
  select(e){
    let index = e.currentTarget.dataset['index'];
    let couponList = this.data.couponList
    couponList[index].select = !couponList[index].select
    this.setData({
      couponList
    })
  },
  // 提成设置
  setCommiss(e) {
    this.setData({
      rewardState: e.currentTarget.dataset.type
    })
  },
  // 提成设置的输入
  bindinput(e){
    let type = e.currentTarget.dataset.type;
    let value = e.detail.value
    if (type == "rewardProportion") {
      this.setData({
        rewardProportion: value
      })
    } else{
      this.setData({
        rewardPrice: value
      })
    }
  },

  //隐藏弹窗
  hideAddCoupon(){
    this.setData({
      isShow:false
    })
  },

  //显示弹窗
  addCoupon(){
    if(this.data.couponList.length>0)
    this.setData({
      isShow:true
    })
    else
    wx.showToast({
      icon:"none",
      title: '暂无优惠券可选',
    })
  },

  //获取优惠券列表
  activityPage(){
    let that =this
    Controllers.getShopCouponList(
      {shopId:wx.getStorageSync('shopId'),sessionId:wx.getStorageSync('token')}).then(res=>{
      let couponList = []
      if(res.code==1){
        res.data.forEach(item => {
          console.log(item)
          if(item.type!=0){
            if(item.type == 1){
              item.typeText="满减优惠券"
            }else if(item.type == 2){
              item.typeText="限时限产品券"
            }else if(item.type == 3){
              item.typeText="体验券"
            }else if(item.type == 4){
              item.typeText="活动礼包券"
            }else if(item.type == 5){
              item.typeText="拉新券"
            }
          }
          item.selectNum=1
          couponList.push(item)
        });
        this.setData({
          couponList
        })
      }
    })
  },
  

  //确认选择
  determine(){
    let addCouponList
    addCouponList = this.data.couponList.filter(item=>item.select)
    this.setData({
      addCouponList,
      isShow:false
    })
    if(this.data.addCouponList.length>0){
      this.setData({
        isGiveCoupon:true
      })
    }else{
      this.setData({
        isGiveCoupon:false
      })
    }

    this.computedCost()
  },

  //获取会员卡详情
  getCardDetail(){
    let value={}
    value.shopId=wx.getStorageSync('shopId')
    value.vipId=this.data.id
    Controllers.vipdetails(value).then(res=>{
      this.setData({
        name:res.data.name,
        image:res.data.image,
        price:res.data.price,
        type:res.data.type,
        timeState:res.data.timeState,
        startTime:res.data.startTime,
        endTime:res.data.endTime,
        effectiveTime:res.data.effectiveTime,
        desc:res.data.desc,
        cost:res.data.cost,
        vip:res.data.vip,
        givePrice:res.data.givePrice,
        giveIntegral:res.data.giveIntegral,
        payLimit:res.data.payLimit,
        isPush:res.data.isPush,
        rewardState:res.data.rewardState,
        rewardPrice:res.data.rewardPrice,
        rewardProportion:res.data.rewardProportion,
      })

      if(res.data.goods&&res.data.goods.length>0){
        res.data.goods.forEach(item=>{
          item.count=item.num
          item.checked=true
          item.id=item.goodsId
        })
        this.setData({
          joinProduct:res.data.goods,
        })
      }


      if(res.data.coupon&&res.data.coupon.length>0){
        res.data.coupon.forEach(item=>{
          item.selectNum=item.couponNum
        })
        this.setData({
          addCouponList:res.data.coupon,
        })
      }
      if(res.data.type==5){
        this.activityPage()
      }

      this.computedCost()
    })
  },

  onLoad: function (options) {
    if(options.id){
      this.setData({
        id:options.id
      })
      this.getCardDetail()
    }

    if(options.type){
      this.setData({
        type:options.type
      })
      if(options.type==5){
        this.activityPage()
      }
      this.getListByTypes()
    }

    // 获取完整的年月日 时分秒，以及默认显示的数组
    var obj1 = dateTimePicker.dateTimePicker();
    var obj2 = dateTimePicker.dateTimePicker();
    this.setData({
      dateTimeArray1: obj1.dateTimeArray,
      dateTime1: obj1.dateTime,
      dateTimeArray2: obj2.dateTimeArray,
      dateTime2: obj2.dateTime,
    });
  },
  onShow(){
    var chooseProduct=this.data.chooseProduct
    // var all=this.data.joinProduct
    var all=[]
    // all.forEach(function(item,index){
    //   chooseProduct.forEach(function(item1,index1){
    //     if(item.id==item1.id){
    //       chooseProduct.splice(index1,1)
    //     }
    //   })
    // })
    if(chooseProduct){
      for(let item of chooseProduct){
        item.num=item.count
      }
      this.setData({
        // joinProduct:all.concat(chooseProduct)
        joinProduct:chooseProduct
      })
      // debugger
      this.computedCost()
    }
  },
  changeDateTime1(e) {
    var date=this.data.dateTimeArray1
    var time=e.detail.value
     this.setData({
      dateTime1: time,
      startTime:date[0][time[0]]+"-"+date[1][time[1]]+"-"+date[2][time[2]]+" "+date[3][time[3]]+":"+date[4][time[4]]
     });
  },
  changeDateTimeColumn1(e) {
    var arr = this.data.dateTime1, dateArr = this.data.dateTimeArray1;
    arr[e.detail.column] = e.detail.value;
    dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);
    this.setData({
      dateTimeArray1: dateArr,
      dateTime1: arr,
    });
  },
  changeDateTime2(e) {
    var date=this.data.dateTimeArray2
    var time=e.detail.value
     this.setData({
      dateTime2: time,
      endTime:date[0][time[0]]+"-"+date[1][time[1]]+"-"+date[2][time[2]]+" "+date[3][time[3]]+":"+date[4][time[4]]
     });
  },
  changeDateTimeColumn2(e) {
    var arr = this.data.dateTime2, dateArr = this.data.dateTimeArray2;
    arr[e.detail.column] = e.detail.value;
    dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);
    this.setData({
      dateTimeArray2: dateArr,
      dateTime2: arr,
    });
  },
  changeinput(e){
    var name=e.currentTarget.dataset.name;
    var val=e.detail.value;
    this.setData({
        [name]:val || ''
    })
  },
  changetype(e){
    this.setData({
      typeval:this.data.typeattr[e.detail.value],
      type:e.detail.value
    })
  },
  settimeState(e){
    this.setData({
      timeState:e.currentTarget.dataset.type,
    })
  },

  changePayLimit(e){
    this.setData({
      payLimit:e.currentTarget.dataset.type,
    })
  },

  addgoods(e){
    let nowListSting = JSON.stringify(this.data.joinProduct);
    wx.navigateTo({
      url: '/pages/settlement/AddGoods/AddGoods?nowList=' + nowListSting,
    })
  },
  cancel(e){
    wx.navigateBack({
      delta: 1
    })
  },
  delete(index){
    this.data.joinProduct.splice(index,1)
    this.setData({
      joinProduct:this.data.joinProduct
    })
  },
  plus(e){
    var index=e.currentTarget.dataset.index
    this.data.joinProduct[index].num++;
    this.data.joinProduct[index].count++;
    this.setData({
      joinProduct:this.data.joinProduct
    })
    this.computedCost()
  },
  mins(e){
    var index=e.currentTarget.dataset.index
    if(this.data.joinProduct[index].num>1){
      this.data.joinProduct[index].num--;
      this.data.joinProduct[index].count--;
      this.setData({
        joinProduct:this.data.joinProduct
      })
    }else{
      this.delete(index)
    }
    this.computedCost()
  },
  changenum(e){
    var index=e.currentTarget.dataset.index
    if(this.data.joinProduct[index].num<1){
      this.data.joinProduct[index].num=1
      this.setData({
        joinProduct:this.data.joinProduct
      })
    }else{
      this.data.joinProduct[index].num=e.detail.value
      this.setData({
        joinProduct:this.data.joinProduct
      })
    }
    this.computedCost()
  },
  vipsave(){
    if(!this.data.name){
        wx.showToast({
          title: '请输入活动名称',
          icon: 'none',
          duration: 2000
        })
        return
    }
    if(!this.data.price){
      wx.showToast({
        title: '请输入会员卡价格',
        icon: 'none',
        duration: 2000
      })
      return
    }
    if(this.data.price<=0){
      wx.showToast({
        title: '会员卡价格价格不能为0',
        icon: 'none',
        duration: 2000
      })
      return
    }
    if(!this.data.startTime || this.data.startTime=='请选择时间'){
      wx.showToast({
        title: '请选择开始时间',
        icon: 'none',
        duration: 2000
      })
      return
    }
    if(!this.data.endTime || this.data.endTime=='请选择时间'){
      wx.showToast({
        title: '请选择结束时间',
        icon: 'none',
        duration: 2000
      })
      return
    }
    

    if(this.data.startTime && this.data.endTime){
      var currentdate = Date.parse(util.formatTime_1(new Date()));
      let startTime=Date.parse(new Date(this.data.startTime.replace(/-/g, '/')));
      let endTime=Date.parse(new Date(this.data.endTime.replace(/-/g, '/')));
      if(startTime>=endTime){
        wx.showToast({
          title: '开始时间不能少于结束时间',
          icon: 'none',
          duration: 2000
        })
        return
      }
      if(currentdate>startTime){
        wx.showToast({
          title: '开始时间不能少于当前时间',
          icon: 'none',
          duration: 2000
        })
        return
      }
      if(currentdate>endTime){
        wx.showToast({
          title: '结束时间不能少于当前时间',
          icon: 'none',
          duration: 2000
        })
        return
      }
    }
    if(this.data.timeState==1 && !this.data.effectiveTime){
        wx.showToast({
          title: '请输入有效天数',
          icon: 'none',
          duration: 2000
        })
        return
    }
  
    let data={};
    data.shopId=wx.getStorageSync('shopId');
    data.name=this.data.name;
    // data.vipId=wx.getStorageSync('accountId');
    data.image=this.data.image || '';
    data.price=this.data.price;
    data.type=this.data.type;
    data.timeState=this.data.timeState;
    data.startTime=this.data.startTime=='请选择时间'?'':this.data.startTime;
    data.endTime=this.data.endTime=='请选择时间'?'':this.data.endTime;
    data.effectiveTime=this.data.effectiveTime;
    data.desc=this.data.desc ||'';
    data.cost=this.data.cost;
    data.giveIntegral=this.data.giveIntegral||''
    data.givePrice=this.data.givePrice||''
    data.vip=this.data.vipTypeList[this.data.vipIndex].id
    data.haveGoods=0
    data.haveCoupon=0
    data.payLimit=this.data.payLimit
    data.rewardState = this.data.rewardState;
    data.rewardProportion = this.data.rewardProportion ? this.data.rewardProportion : '';
    data.rewardPrice = this.data.rewardPrice ? this.data.rewardPrice : '';
    if(this.data.joinProduct.length>0){
      data.haveGoods=1
      let goodsIdNum=[]
      for(let item of this.data.joinProduct){
        goodsIdNum.push(item.id+'-'+item.num);
      }
      data.goodsIdNum=goodsIdNum.join(',')
    }
    if(this.data.addCouponList.length>0){
      data.haveCoupon=1
      console.log(data.haveCoupon)
      let couponIdNum=[]
      for(let item of this.data.addCouponList){
        couponIdNum.push(item.id+'-'+item.selectNum);
      }
      data.couponIdNum=couponIdNum.join(',')
    }
    if(this.data.isloading){
      return
    }
    this.setData({
      isloading:true
    })

    if(this.data.id){
      data.id=this.data.id
      Controllers.updateOpenVip(data).then(res=>{
        wx.showToast({
          title: '修改成功！',
          icon: 'success',
          duration: 2000
        })
        setTimeout(res => {
          wx.navigateBack({ //返回
            delta: 1
          })
           that.setData({
            isloading:false
           })
        },2000)
      })
    }else{
      Controllers.vipsave(data).then(res => {
        wx.showToast({
          title: '添加成功！',
          icon: 'success',
          duration: 2000
        })
        var that=this
        setTimeout(res => {
          wx.navigateBack({ //返回
            delta: 1
          })
           that.setData({
            isloading:false
           })
        },2000)
      }).catch(()=>{
        this.setData({
          isloading:false
        })
      })
    }
  },

  //选择会员
  changeVipType(e){
    let index=e.detail.value
    this.setData({
      vipIndex:index
    })
  }
})
